package org.finesys.gateway.handler;

import org.finesys.common.core.module.R;
import org.finesys.gateway.util.WebFluxUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.BodyExtractors;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.anji.captcha.model.common.CaptchaTypeEnum;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import reactor.core.publisher.Mono;


/**
 * 验证码检查
 */
@Component
@RequiredArgsConstructor
public class AjImageCodeCheckHandler implements HandlerFunction<ServerResponse> {
    private final CaptchaService captchaService;

    @Override
    @SneakyThrows
    public Mono<ServerResponse> handle(@NonNull ServerRequest request) {


        return request.body(BodyExtractors.toMono(CaptchaVO.class)).flatMap(captchaVO -> {
            captchaVO.setBrowserInfo(WebFluxUtil.getClientIP(request));
            captchaVO.setCaptchaType(CaptchaTypeEnum.BLOCKPUZZLE.getCodeValue());
            if (!StringUtils.hasText(captchaVO.getPointJson())) {
                captchaVO.setPointJson(request.queryParam("pointJson").get());
            }
            if (!StringUtils.hasText(captchaVO.getToken())) {
                captchaVO.setToken(request.queryParam("token").get());
            }
            ResponseModel responseModel = captchaService.check(captchaVO);
            return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(R.success(responseModel)));
        });
    }
}
